var ___systemIsCb = false;
var ___locationdata = [];

function changeClocationSelect(o, index) {

	var select_plocation = document.getElementById("select_plocation");
	var select_clocation = document.getElementById("select_clocation");
	//清空上次的选项
	select_clocation.options.length = 0;
	//获取省一级的下拉列表选中的索引
	//var index=select_plocation.selectedIndex;

	//logDebug(index);
	//logDebug(___locationdata[index]);
	for (var i = 0; i < ___locationdata[index]['_childs'].length; i++) {
		select_clocation.options[i] = new Option(___locationdata[index]['_childs'][i]['name'], ___locationdata[index][
			'_childs'
		][i]['id']);
	}
}

function initBaseData() {

	ScreenReq.loadLocationData({}, function(data) {
		Cloading.hide();
		if (data && data['list']) {
			var select_plocation = document.getElementById("select_plocation");
			//清空上次的选项
			select_plocation.options.length = 0;
			___locationdata = data['list'];
			for (var i = 0; i < ___locationdata.length; i++) {
				select_plocation.options[i] = new Option(___locationdata[i]['name'], ___locationdata[i]['id']);
			}

			changeClocationSelect(null, 0);
		}
	});
}


//初始化部门组织树
function initDepartSelect(){
	var zNodes = [];
	ScreenReq.initDepartSelect({},function(info){
			if(info["code"] == 0){
				$("#verify-form").hide();
				$("#regdevice_form").show();
				zNodes = info["data"];
				var defaults = {

					zNodes: zNodes,
					height: 233,
					filter: true,
					searchShowParent: true,
					chkStyle: "radio"
				};
				var selectObj = $("#depart").treeSelect(defaults);
				$("#submitDeviceInfo").click(function () {

					var data = $("#regdevice_form").serializeJson();

					data['locationId'] = selectObj.val()[0];
					updateClientInfo(data);

				})
			}else{
				$("#verify-form").show();
				$("#regdevice_form").hide();
				Qmsg.error(info["msg"]);
			}
	})

}

//验证租户代码和密码
function submitVerifyInfo(){
	var formJSon = $("#verify-form").serializeJson();
	//console.log(JSON.stringify(formJSon));

	if(null == formJSon['subdomain'] || '' == formJSon['subdomain']){
		Qmsg.error('企业代码不能为空!');
		return false;
	}

	formJSon['sysinfo'] = JSON.stringify(____clientStaticData);

	var device = VisualConst.getCustomDevice();

	formJSon["id"] = device["deviceid"];
	formJSon["deviceid"] = device["deviceid"];
	formJSon["appid"] = VisualConst.getAppCfg()['comm']['appid'];
	//console.log(JSON.stringify(formJSon));

	ScreenReq.clientLogin(formJSon,function(info){
		console.log(info);
		if(info["code"] == 0){
			var tenantId = info["data"]["id"] + '';

			//租户id写入文件
			Lib.setStorage('_tenantId',tenantId);
			Lib.setStorage('_token',info['token']);
			Lib.setStorage('_deviceId',device["deviceid"]);

			initDepartSelect();
			$("#tenantName").html(info["data"]["name"]);
			Qmsg.success("登陆成功,请选择设备所属部门!");
		}else{
			Qmsg.error(info["msg"]);
		}

	})
}

/**
 * 多租户版本，绑定设备信息，绑定租户下部门
 *
 * */
function updateClientInfo(data) {


	var device = VisualConst.getCustomDevice(____clientStaticData["system"])

	data["id"] = device["deviceid"];
	ScreenReq.updateClientInfo(
		data,
		function(result) {
			console.log(result);
			if (result["code"] == 0) {
				//绑定成功
				Qmsg.success("绑定成功");

				document.getElementById("client_location").style.display = "none";
				loadClientInfo();
			} else {
				//console.log(result);
			}
		}
	);
}



/**
 * 绑定设备信息位置，弃用，改用多租户
 *
 * */
function submitDeviceInfo() {
	var select_plocation = document.getElementById("select_plocation");
	var select_clocation = document.getElementById("select_clocation");
	var remark = document.getElementById("input_remark").value;
	// var tenantCode = document.getElementById("input_tenantCode").value;
	var index = select_clocation.selectedIndex;
	var text = select_clocation.options[index].text;
	var value = select_clocation.options[index].value;

	var data = {
		"locationRemark": remark,
		"locationId": value,
		"locationName": text,
		"sysinfo": JSON.stringify(____clientStaticData)
	};

	var device = VisualConst.getCustomDevice();

	data["id"] = device["deviceid"];
	data["deviceid"] = device["deviceid"];
	data["appid"] = device['appid'];

	logDebug("------------------");
	logDebug(JSON.stringify(data));
	ScreenReq.regClientInfo(
		data,
		function(result) {
			logDebug(JSON.stringify(result));
			if (result["code"] == 0) {
				//绑定成功
				document.getElementById("client_location").style.display = "none";
				loadClientInfo();
			} else {
				logDebug(result);
			}
		}
	);
}
function showSetServerInfo(){
	//初始化表单
	var data = VisualConst.getServerInfo();
	 // console.log("VisualConst.getServerInfo",JSON.stringify(data));
	var wsParams = _cfg.getRCfg();
	// console.log("VisualConst.getRCfg",JSON.stringify(VisualConst.getAppCfg()));
	data["port"] = data["port"] || wsParams["ws_port"];
	$("#verify-form").find(':input').each(function() {
		$(this).val(data[$(this).attr('name')]);
	});
	//显示表单界面
	document.getElementById("client_location").style.display = "block";
}
function hideSetServerInfo(){
	document.getElementById("client_location").style.display = "none";
}
function cancelSetServerInfo(){
	hideSetServerInfo();
	$("#verify-form")[0].reset();
}
function submitSetServerInfo(){
	var formJSon = $("#verify-form").serializeJson();
	//console.log(JSON.stringify(formJSon));

	if(null == formJSon['ip'] || '' == formJSon['ip']){
		Qmsg.error('请填写服务器IP');
		return false;
	}
	if(null == formJSon['port'] || '' == formJSon['port']){
		Qmsg.error('请填写服务器PORT');
		return false;
	}

	// formJSon['sysinfo'] = JSON.stringify(____clientStaticData);

	var device = VisualConst.getCustomDevice();
	formJSon["id"] = device["deviceid"];
	formJSon["deviceid"] = device["deviceid"];
	formJSon["appid"] = VisualConst.getAppCfg()['comm']['appid'];
	// console.log(JSON.stringify(formJSon));

	//保存配置信息到配置文件
	VisualConst.setServerInfo(formJSon);
	//刷新首页
	//重连服务 
	// loadMainPage();
	window.location.reload();
}
function loadClientInfo() {
	// Cloading.show();
	Cloading.hide();
	
	//不在从后端接口获取设备信息，本地读取，本地显示
	var contentMsg = VisualConst.getLastContent();
	logDebug(["contentMsg=====",JSON.stringify(contentMsg)]);
	//未获取到本地缓存的内容
	if (  !contentMsg["contentlist"] || (contentMsg["contentlist"] && contentMsg["contentlist"].length==0)) {
		//获取官方示例
		pushLoadContentPage(contentMsg);
		// VisualReq.loadExmple(function(body){
		// 	//console.log("body",body) // 输出网页内容
		// 	contentMsg = {
		// 		"pushtype": 'screens',
		// 		"contentlist": body["data"]
		// 	};
		// 	// pushLoadContentPage(contentMsg);
		// })
	}else{
		pushLoadContentPage(contentMsg);
	}
}

function reConnectOpen() {
	Cloading.show();
	//initBaseData(); //初始化位置数据
	loadClientInfo(); //加载设备信息
}

function loadMainPage() {
	Cloading.show();
	//显示客户端版本
	plus.runtime.getProperty( plus.runtime.appid, function(wgtinfo){
		var sys_version = wgtinfo.version;//plus.runtime.version;
		logDebug(sys_version);
		document.getElementById("sys_version").innerHTML = sys_version;
	});
	logDebug("navigator.userAgent=" + JSON.stringify(navigator.userAgent));
	//获取客户端的设备信息
	VisualConst.getClientStaticData(function(data) {
		Cloading.hide();
		//document.getElementById('sys_info').innerHTML = VisualConst.____renderSysinfo(data);
		connectWsServer(); //链接socket服务
		plus.navigator.closeSplashscreen();//关闭5+自带的启动画面
	});

	//版本更新检查
	// ScreenReq.checkUpdate();
}

function showMainPage(){
	loadIndexPage();//显示注册、默认首页页面
	plus.device.getInfo({
		success:function(e){
			logDebug('getDeviceInfo success: '+JSON.stringify(e));
			plus.device.uuid = e.uuid;
			plus.device.imei = e.imei;
			plus.device.imsi = e.imsi;
			
			loadMainPage(); //加载主页面内容
			logDebug("=========================" + window.screen.width + "X" + window.screen.height);
			logDebug("=========================" + JSON.stringify(VisualConst.getScreenSize()) )
			
		},
		fail:function(e){
			logDebug('getDeviceInfo failed: '+JSON.stringify(e));
			//无法识别设备
			plus.nativeUI.toast("无法识别设备，请联系管理员！");
		}
	});
}
mui.plusReady(function() {
	

	// plus.io.getFileInfo({
	// 	"filePath":"_www/res/conf/cfg.js",
	// 	"success":function(f){
	// 		console.log(JSON.stringify(f));
	// 	}
	// });
	// showStartPage();
	plus.device.setWakelock(true); //设置不允许休眠，一直亮屏
	var old_back = mui.back;
	var backFirst = null;
	mui.back = function() {
		var topView = plus.webview.getTopWebview();
		logDebug(["按下了返回键",topView.id,topView.opener()])
		var first = null;
		//显示上一个界面；
		if(topView.opener()){
			//topView.close(); //返回上一页面
			// var btn = ["确定","取消"];
			// mui.confirm('确认关闭当前窗口？','Hello MUI',btn,function(e){
			// 	if(e.index==0){
			// 		//执行mui封装好的窗口关闭逻辑；
			// 		topView.close()
			// 	}
			// });
			//首次按键，提示‘再按一次退出应用’  
			if (!backFirst) {  
				backFirst = new Date().getTime();  
				mui.toast('再按一次关闭当前窗口');  
				setTimeout(function() {  
					backFirst = null;  
				}, 1000);  
			} else {  
				if ((new Date()).getTime() - backFirst < 1000) {  
					// plus.runtime.quit();  
					topView.close();
					_contentWindows[topView.id] = null;
				}  
			}  
		}else{
			old_back();
		}
		// topView.canBack(function(e) { //监听webview窗口是否可以返回
		// 	console.log("e.canBack",e.canBack,e.index);
		// 	if (e.canBack) { //可以返回
		// 		topView.back(); //返回上一页面
		// 	} else { //不可以返回
		// 		//old_back();
		// 	}
		// 	topView.close(); //返回上一页面
		// });
		//继续当前页面原有返回逻辑
	}
	//加载配置
	
	//显示启动页面，延迟展示首页
	setTimeout(showMainPage,200);
});
